package com.hkts.management.cargoapply.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.management.cargo.entity.HktsCargo;
import com.hkts.management.cargo.mapper.HktsCargoMapper;
import com.hkts.management.cargoapply.service.IHktsCargoApplyService;
import com.hkts.management.cargoapply.entity.HktsCargoApply;
import com.hkts.management.cargoapply.mapper.HktsCargoApplyMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.management.common.mq.*;
import com.hkts.management.common.utils.BeanConvertUtils;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.common.vo.UserAndRealNameVo;
import com.hkts.management.contract.entity.HktsContract;
import com.hkts.management.contract.mapper.HktsContractMapper;
import com.hkts.management.feign.FeignInterface;
import com.hkts.management.feign.FrontInterface;
import com.hkts.management.model.TO.HontUserTo;
import com.hkts.management.model.VO.HktsCargoApplyOnPCVo;
import com.hkts.management.model.VO.UserVo;
import com.hkts.management.model.enums.OrderStatusEnum;
import com.hkts.management.model.enums.OrderTypeEnum;
import com.hkts.management.order.entity.HktsOrder;
import com.hkts.management.order.mapper.HktsOrderMapper;
import com.hkts.management.order.service.IHktsOrderService;
import com.hkts.management.orderrecord.service.IHktsOrderRecordService;
import com.hkts.management.returnfee.service.IHktsReturnFailService;
import com.hkts.management.utils.DateConverUtils;
import com.hkts.management.utils.PayConstants;
import com.hkts.management.utils.PayProperties;
/*import com.xunhu.hupj.pay.sdk.DefaultXunhuPayClient;
import com.xunhu.hupj.pay.sdk.request.OrderRefundRequest;
import com.xunhu.hupj.pay.sdk.response.OrderRefundResponse;*/
import com.hkts.management.utils.RegionConverUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2021-04-22
 */
@Service
@Transactional
@Slf4j
public class HktsCargoApplyServiceImpl extends ServiceImpl<HktsCargoApplyMapper, HktsCargoApply> implements IHktsCargoApplyService {

    @Autowired
    private PayProperties payProperties;

    @Autowired
    private HktsCargoApplyMapper hktsCargoApplyMapper;

    @Autowired
    private HktsCargoMapper cargoMapper;

    @Autowired
    private HktsOrderMapper orderMapper;

    @Autowired
    private HktsCargoApplyMapper cargoApplyMapper;

    @Autowired
    private IHktsOrderService orderService;

    @Autowired
    private IHktsOrderRecordService orderRecordService;

    @Autowired
    private HktsContractMapper contractMapper;

    @Autowired
    public IHktsReturnFailService iHktsReturnFailService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RegionConverUtil regionConverUtil;
    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private FrontInterface frontInterface;

    @Override
    public IPage<HktsCargoApply> selectPage(Page<HktsCargoApply> page, HktsCargoApply hktsCargoApply) {
        QueryWrapper<HktsCargoApply> query = Wrappers.query();
        QueryWrapper<HktsCargoApply> entityWrapper = getEntityWrapper(query, hktsCargoApply);
        return hktsCargoApplyMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HktsCargoApply> selectList(HktsCargoApply hktsCargoApply) {
        QueryWrapper<HktsCargoApply> query = Wrappers.query();
        QueryWrapper<HktsCargoApply> entityWrapper = getEntityWrapper(query, hktsCargoApply);
        return hktsCargoApplyMapper.selectList(entityWrapper);
    }


    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsCargoApply> getEntityWrapper(QueryWrapper<HktsCargoApply> entityWrapper, HktsCargoApply hktsCargoApply) {
        if (StringUtils.isNotBlank(hktsCargoApply.getCargoId())) {
            entityWrapper.lambda().eq(HktsCargoApply::getCargoId, hktsCargoApply.getCargoId());
        }
        return entityWrapper;
    }
    public int selectCount(HktsCargoApply hktsCargoApply) {
        QueryWrapper<HktsCargoApply> query = Wrappers.query();
        query.lambda().eq(HktsCargoApply::getCargoId,hktsCargoApply.getCargoId());
        QueryWrapper<HktsCargoApply> entityWrapper = getEntityWrapper(query, hktsCargoApply);
        return hktsCargoApplyMapper.selectCount(entityWrapper);
    }

    @Override
    public int getCargoLanelByCargoId(String cargoId,Integer check_status){
        QueryWrapper<HktsCargoApply> query = Wrappers.query();
        query.lambda().eq(HktsCargoApply::getCargoId,cargoId)
                .eq(check_status!=null,HktsCargoApply::getCheckStatus,check_status);
        Integer integer = hktsCargoApplyMapper.selectCount(query);
        return integer;
    }

    @Override
    public HktsCargoApply getCargoApplyByCargoIdAndDriver(String cargoId,String driverId){
        QueryWrapper<HktsCargoApply> query = Wrappers.query();
        query.lambda().eq(HktsCargoApply::getCargoId,cargoId)
                .eq(HktsCargoApply::getDriverId,driverId);
        HktsCargoApply hktsCargoApply = hktsCargoApplyMapper.selectOne(query);
        return hktsCargoApply;
    }

    /**
     * 修改报名状态
     * @param orderId
     * @param check_status
     * @return
     */
    @Override
    public Result updateCheckStatus(String orderId, Integer check_status){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        String message="";

        HktsOrder order = orderMapper.selectById(orderId);
        if (order.getOrderSubstate() == OrderStatusEnum.DRIVER_CONFIRMED.getValue()){
            return ResultUtil.error("该订单为指定司机,请联系司机确认！");
        }
        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        HktsCargoApply hktsCargoApply = hktsCargoApplyMapper.selectById(order.getApplyId());
        String format = "YYYY-MM-dd hh:mm:ss";


        // TODO 通知司机同意或拒绝的消息，拒绝后退款
        String msgCode="";
        if (check_status == 0){
            List<Integer> status = new ArrayList<>(4);
            status.add(1);
            status.add(2);
            status.add(3);
            status.add(4);
            QueryWrapper<HktsOrder> queryOrder = Wrappers.query();
            queryOrder.lambda().eq(HktsOrder::getDriverId, hktsCargoApply.getDriverId()).in(HktsOrder::getOrderSubstate, status);
            int orderCount = orderMapper.selectCount(queryOrder);
            if (orderCount > 0) {
                Result<Object> result = ResultUtil.data(null);
                result.setMessage("该司机有未完成的订单");
                return result;
            }
            msgCode=IMessage.ORDER_CONFIRM;
            hktsCargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(), PayConstants.SUCCESSFUL_REGISTRATION,hktsCargoApply.getDepositStatus(),LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
            orderMapper.updateByOrderId(order.getId(), OrderTypeEnum.SIGN_CONTRACT, OrderStatusEnum.DRAFT_CONTRACT.getValue(),LocalDateTime.now());
            orderRecordService.addOrderRecord(order.getId(),hktsCargo.getUsername(),OrderStatusEnum.DRAFT_CONTRACT.getValue());
            message="通过报名成功！";
        }if (check_status == 1){
            msgCode=IMessage.CANCEL;

            orderMapper.updateByOrderId(order.getId(), OrderTypeEnum.CANCEL, OrderStatusEnum.REFUSE_CANCEL.getValue(),LocalDateTime.now());
            contractMapper.updateContractByOrderId(order.getId());
            orderRecordService.addOrderRecord(order.getId(),hktsCargo.getUsername(),OrderStatusEnum.REFUSE_CANCEL.getValue());
            // TODO 退款
            if(hktsCargoApply.getDepositStatus() == PayConstants.PAID){
                cargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(),PayConstants.AUDIT_FAILED,PayConstants.REFUND,LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
                iHktsReturnFailService.returnFee(hktsCargoApply);
            }else {
                hktsCargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(), PayConstants.AUDIT_FAILED,hktsCargoApply.getDepositStatus(),LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
            }
            message="拒绝报名成功！";
        }
        //es同步
        HktsOrder orderData = orderMapper.selectById(orderId);
        //TODO es同步数据
        orderService.updateOrderOnEs(orderData.getId(),orderData.getOrderStatus(),orderData.getOrderSubstate());
        //发送消息
        String finalMsgCode = msgCode;
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                QueryWrapper<HktsContract> queryContract = Wrappers.query();
                queryContract.lambda().eq(HktsContract::getOrderId,order.getId());
                HktsContract contract = contractMapper.selectOne(queryContract);

                String address=regionConverUtil.regionCoverStr(Integer.valueOf(contract.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(contract.getEndArea()));
                Map<String, Object> params=new HashMap<>();
                params.put("name", feignInterface.remoteUserInfo().getNickName());
                params.put("time", contract.getLoadingTime().toLocalDate());
                params.put("address",address);
                MsgExtras msgExtras=new MsgExtras();
                msgExtras.setOrderId(order.getId());
                String messageId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                IMessage msg = new IMessage.Builder()
                        .messageId(messageId)
                        .msgCode(finalMsgCode)
                        .fromUserId(orderData.getShipper())
                        .toUserId(orderData.getDriverId())
                        .mineType(MineType.TEMPLATE.getIndex())
                        .chatType(ChatType.UNICAST.getIndex())
                        .msgType(MsgType.JUMPTO.getIndex())
                        .param(params)
                        .extras(msgExtras)
                        .build();
                Map<?,?> msgMap= BeanConvertUtils.objectToMap(msg);
                amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, FanoutRabbitConfig.ASSIFN, msgMap);
            }
        });
        return ResultUtil.success(message);
    }

    @Override
    public Result<HktsCargoApplyOnPCVo> getApplyInfo(String applyId) {
        HktsCargoApply cargoApply=hktsCargoApplyMapper.selectById(applyId);
        HktsCargoApplyOnPCVo cargoApplyOnPCVo=BeanConvertUtils.copy(cargoApply,HktsCargoApplyOnPCVo.class);
        Result<UserAndRealNameVo> userAndRealNameVoResult=frontInterface.getDriverInfoByUserId(cargoApply.getDriverId());
        log.info("用户id{}用户信息{}",cargoApply.getDriverId(),userAndRealNameVoResult);
        if(userAndRealNameVoResult.isSuccess()&&userAndRealNameVoResult.getResult()!=null) {
            UserAndRealNameVo userAndRealNameVo = userAndRealNameVoResult.getResult();
            cargoApplyOnPCVo.setDriverName(userAndRealNameVo.getDriverName());
            cargoApplyOnPCVo.setLicencePlate(userAndRealNameVo.getCarCode());
            cargoApplyOnPCVo.setPhone(userAndRealNameVo.getMobile());
            String carInfo=userAndRealNameVo.getEhicleType()+"/"+userAndRealNameVo.getVehicleLength();
            cargoApplyOnPCVo.setCarInfo(carInfo);
            cargoApplyOnPCVo.setApproval(userAndRealNameVo.getApproval());
            if("2".equals(userAndRealNameVo.getApproval())){
                Map<String,Object> map=userAndRealNameVo.getApprovalUrl();
                if(map!=null){
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime ldt = LocalDateTime.parse("2017-09-28 17:07:05",df);
                    int count= DateConverUtils.intervalDays(ldt);
                    cargoApplyOnPCVo.setApprovalTime(count);
                }
            }
        }
       Integer count= orderService.countOrder(cargoApply.getDriverId(),4);
        cargoApplyOnPCVo.setTradingCount(count);
        if(cargoApply.getCheckStatus()==0){
            HktsCargo hktsCargo=cargoMapper.selectById(cargoApply.getCargoId());
            Result<UserVo> result=feignInterface.getUserByuserId(hktsCargo.getUserId());
            if(result.isSuccess()){
                UserVo userVo=result.getResult();
                cargoApplyOnPCVo.setOperationName(userVo.getNickName());
            }else {
                log.info("获取报名信息时，操作人为空");
            }
        }
        return ResultUtil.data(cargoApplyOnPCVo);
    }
}
